//
//  HomeCell2.m
//  警用舆情平台
//
//  Created by 魏强 on 15/5/14.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "HomeCell2.h"
#import "KDHomeRequestTool.h"
#import "KDHomeListPageCellModel.h"
#import "KDHomeListPageCollectParam.h"
#import "KDHomeListPageCollectResult.h"
#import "KDHomeListPageUnCollectResult.h"
#import "KDHomeListPageUnCollectParam.h"
#import "SVProgressHUD.h"
@interface HomeCell2 ()
@property (weak, nonatomic) IBOutlet UIButton *titleBtn;
@property (weak, nonatomic) IBOutlet UIButton *timeLabel;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet UIButton *reportBtn;
/**
 *  相关
 */
@property (weak, nonatomic) IBOutlet UIButton *relatedBtn;
/**
 *  作者label
 */
@property (weak, nonatomic) IBOutlet UILabel *authorLabel;

/**
 *  来源label
 */
@property (weak, nonatomic) IBOutlet UILabel *comeFromLabel;
/**
 *  数字
 */
@property (weak, nonatomic) IBOutlet UILabel *numLb;
- (IBAction)collectBtnClick:(id)sender;
- (IBAction)reportBtnClick:(id)sender;

@property (weak, nonatomic) IBOutlet UIView *underView;
/**
 *  数字lb的宽度约束
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *numLb_constraint_W;
/**
 *  相关文字距离中心的偏离
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *relationLb_CenterX_Constraint;
@end
@implementation HomeCell2

- (void)awakeFromNib {
    // Initialization code
}
//- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
//    if (highlighted == YES && iOS7 && screenH == 480) {
//        [self.titleBtn setTitleColor:WQColor(178, 182, 184) forState:UIControlStateNormal];
//    }
//    [super setHighlighted:highlighted animated:animated];
//}

/**
 *  当cell被选中时，就调用这个方法,让子体变灰
 *
 *  @param highlighted 是否被选中
 */
- (void)setHighlight:(BOOL)highlight{
    _highlight = highlight;
    if (highlight) {
        [self.titleBtn setTitleColor:WQColor(178, 182, 184) forState:UIControlStateNormal];
        self.model.read = YES;
    }
    
//    [self layoutIfNeeded];
}
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *cellId =@"homeCell2";
    UINib *xib = [UINib nibWithNibName:@"HomeCell2" bundle:nil];
    [tableView registerNib:xib forCellReuseIdentifier:cellId];
    HomeCell2 *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell =[[[NSBundle mainBundle]loadNibNamed:@"HomeCell2" owner:self options:nil]lastObject];
    }
//    HomeCell2 *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
    cell.contentView.backgroundColor = BackGroundColor;
//    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
//    cell.underView.layer.cornerRadius = 5.0f;
//    cell.underView.layer.borderWidth = 0.2f;
//    cell.underView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.titleBtn.titleLabel.numberOfLines = 2;
    //监听收藏状态改变之后的通知
    [[NSNotificationCenter defaultCenter] addObserver:cell selector:@selector(SingleWebViewControllerCollectionBtnClick:) name:@"SingleWebViewControllerCollectionBtnClickToHomeNoty" object:nil];
    //监听上报成功之后的通知
    [[NSNotificationCenter defaultCenter] addObserver:cell selector:@selector(ReportControllerReportSeccess:) name:@"ReportControllerReportSeccessToHomeNoty" object:nil];
    return cell;
}

- (void)setModel:(KDHomeListPageCellModel *)model
{
    _model = model;
    if (self.model) {
        NSString * str = [self.model.title stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
        NSString *title = [str stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
        [self.titleBtn setTitle:title forState:UIControlStateNormal];
        if (self.model.read) {
            [self.titleBtn setTitleColor:WQColor(178, 182, 184) forState:UIControlStateNormal];
        }else{
            [self.titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        
        [self.timeLabel setTitle:self.model.date forState:UIControlStateNormal];
        if (self.model.topicCount == 1) {//只有一条的时候就不显示
            self.numLb.text = [NSString stringWithFormat:@"%ld", (long)self.model.topicCount - 1];
            self.numLb.hidden = YES;
            self.relatedBtn.enabled = NO;
            self.numLb_constraint_W.constant = 0;
            self.relationLb_CenterX_Constraint.constant = 0;
        }else{
            self.numLb.text = [NSString stringWithFormat:@"%ld", (long)self.model.topicCount];
            self.relatedBtn.enabled = YES;
            self.numLb.hidden = NO
            ;
            self.relationLb_CenterX_Constraint.constant = 17;
            if (self.model.topicCount < 10) {//条数小于10 的时候变圆
                self.numLb_constraint_W.constant = 13;
                self.numLb.layer.cornerRadius = 6;
                self.numLb.clipsToBounds = YES;
                if (self.model.topicCount-1 == 0) {
                    self.numLb.backgroundColor = [UIColor grayColor];
                }else{
                    self.numLb.backgroundColor = WQColor(255, 106, 18);
                }
            }else{
                self.numLb.layer.cornerRadius = 4;
                self.numLb_constraint_W.constant = 30;
                self.numLb.backgroundColor = WQColor(255, 106, 18);
            }
        }
        self.collectBtn.selected = self.model.isSave;
        self.reportBtn.selected = self.model.report;
        self.comeFromLabel.text = self.model.source;
        self.authorLabel.text = self.model.author;
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
//        if (CGRectGetMaxX(self.timeLabel.frame) > self.collectBtn.x) {
//            NSString *str = [self.model.date substringToIndex:10];
//            self.model.date = str;
//             [self.timeLabel setTitle:self.model.date forState:UIControlStateNormal];
//        }
//    }

}

#pragma mark - 点击事件区

/**
 *  点击收藏按钮
 */
- (IBAction)collectBtnClick:(id)sender {
    
    if (!self.collectBtn.selected) {//点中收藏
        //给服务器发送“已收藏的信息”
        [self sendCollectData];
    }else{//取消收藏
        [self sendUncollectData];
    }
    
}
- (void)sendCollectData
{
    KDAccount *account = [KDAccountTool account];
    KDHomeListPageCollectParam *param = [[KDHomeListPageCollectParam alloc]init];
    param.method = @"addFavorite";
    param.docId = self.model.docId;
    param.url = self.model.url;
    param.token = account.token;
    [KDHomeRequestTool sendCollectDataWithParam:param success:^(KDHomeListPageCollectResult *responseObejct) {
        [SVProgressHUD showSuccessWithStatus:@"收藏成功！" maskType:SVProgressHUDMaskTypeGradient];
//        KDLog(@"%@",responseObejct.status);
        self.model.isSave = !self.model.isSave;
        self.collectBtn.selected = self.model.isSave;
    } faiure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"收藏失败！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@",error);
    }];
}
- (void)sendUncollectData{
      KDAccount *account = [KDAccountTool account];
    KDHomeListPageUnCollectParam *param = [[KDHomeListPageUnCollectParam alloc]init];
    param.method = @"deleteFav";
    param.token = account.token;
    param.docId = self.model.docId;
    [KDHomeRequestTool sendUnCollectDataWithParam:param success:^(KDHomeListPageUnCollectResult *responseObejct) {
        [SVProgressHUD showSuccessWithStatus:@"取消收藏成功！" maskType:SVProgressHUDMaskTypeGradient];
//        KDLog(@"%@",responseObejct.status);
        self.model.isSave = !self.model.isSave;
        self.collectBtn.selected = self.model.isSave;
    } faiure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"取消收藏失败！" maskType:SVProgressHUDMaskTypeGradient];
        KDLog(@"%@",error);
    }];
    
}
- (IBAction)reportBtnClick:(id)sender {

    if (_delegate &&[_delegate respondsToSelector:@selector(homeCell2:reportBtnClick:)]) {
        [_delegate homeCell2:self reportBtnClick:sender];
    }
    
}

/**
 *  相关按钮被点击了
 */
- (IBAction)relatedBtnClick:(UIButton *)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(homeCell2:relationBtnClick:)]) {
        [_delegate homeCell2:self relationBtnClick:sender];
    }
}

#pragma mark - 通知接收区
- (void)SingleWebViewControllerCollectionBtnClick:(NSNotification *)noty{
    NSString *docid = noty.userInfo[@"docid"];
    if ([docid isEqualToString: self.model.docId]) {
       self.model.isSave = [noty.userInfo[@"isCollect"] boolValue];
        self.collectBtn.selected = self.model.isSave;
    }
}
- (void)ReportControllerReportSeccess:(NSNotification *)noty{
    NSString *docid = noty.userInfo[@"docid"];
    if ([docid isEqualToString: self.model.docId]) {
        self.model.report = YES;
        self.reportBtn.selected = self.model.report;
    }
}
@end
